// 测试多线程, 监控弹窗

const { Worker, isMainThread, parentPort } = require('worker_threads');
const { chromium } = require('playwright');

// 主线程逻辑
async function mainThreadLogic() {
  const browser = await chromium.launch();
  const page = await browser.newPage();

  // 导航到页面
  await page.goto('https://example.com');

  // 模拟触发弹窗（例如点击按钮）
  await page.click('button#trigger-popup');

  // 启动 Worker 线程监控弹窗
  const worker = new Worker(__filename, {
    workerData: { page },
  });

  // 监听 Worker 线程的消息
  worker.on('message', (msg) => {
    console.log('Main thread received:', msg);
  });

  // 等待 Worker 线程完成
  worker.on('exit', () => {
    browser.close();
  });
}

// Worker 线程逻辑
function workerThreadLogic() {
  const { page } = require('worker_threads').workerData;

  (async () => {
    // 监听弹窗事件
    page.on('dialog', async (dialog) => {
      console.log('Worker thread detected dialog:', dialog.message());
      // 处理弹框（例如接受或取消）
      await dialog.accept();
      parentPort.postMessage('Dialog handled');
    });

    // 保持 Worker 线程运行
    setInterval(() => {}, 1000);
  })();
}

// 判断是否是主线程并执行相应逻辑
if (isMainThread) {
  module.exports = {
    start: mainThreadLogic,
  };
} else {
  workerThreadLogic();
}